# -*- coding: utf-8 -*-
import time

import pytest
import uvicorn
from fastapi import FastAPI, APIRouter, Depends, Request, Response
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError, HTTPException
from fastapi.responses import PlainTextResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from tutorial import chapter01, chapter02, chapter03, chapter04, chapter05, chapter06
from coronavirus import coronavirus_app

app = FastAPI(
    title="FastAPI Tutorial And Cornonavirus Tracker API Docs",
    description="FastAPI教程和病毒跟踪接口文档.",
    version="1.0.0",
    docs_url="/docs",
    redoc_url='/redocs',
    # dependencies=[Depends(verify_key), Depends(verify_token)]
)

# 将静态文件夹挂载到FastAPI
app.mount(path='/coronavirus/static', app=StaticFiles(directory='./coronavirus/static'), name='static')

# 重写HTTPException异常处理
# @app.exception_handler(StarletteHTTPException)
# async def http_exception_handler(request, exception):
#     """
#
#     :param request:
#     :param exception:
#     :return:
#     """
#     return PlainTextResponse(str(exception.detail), status_code=exception.status_code)
#
# @app.exception_handler(RequestValidationError)
# async def validation_exception_handler(request, exception):
#     """
#
#     :param request:
#     :param exception:
#     :return:
#     """
#     return PlainTextResponse(str(exception), status_code=404)


# 中间件
@app.middleware('http')
# call_next将request请求作为参数
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    # 添加自定义请求头，以“X-”开头
    response.headers['X-Process-Time'] = str(process_time)
    return response

# 加载中间件 跨域资源共享
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://127.0.0.1",
        "http://127.0.0.1:8080"
    ],
    allow_methods=['*'],
    allow_headers=['*']
)


# swagger接口文件分组
app.include_router(chapter01, prefix='/chapter01', tags=['第一章.请求参数和验证'])
app.include_router(chapter02, prefix='/chapter02', tags=['第二章.响应处理和FastAPI配置'])
app.include_router(chapter03, prefix='/chapter03', tags=['第三章.依赖注入系统'])
app.include_router(chapter04, prefix='/chapter04', tags=['第四章.授权认证'])
app.include_router(chapter05, prefix='/chapter05', tags=['第五章.FastAPI 项目中配置 SQLAlchemy ORM'])
app.include_router(chapter06, prefix='/chapter06', tags=['第八章.中间件,CORS,后台任务，测试用例'])
app.include_router(coronavirus_app, prefix='/coronavirus_app', tags=['第六章.新冠病毒'])


if __name__ == '__main__':
    # uvicorn.run(app=app, host="127.0.0.1", port=8080, reload=True, debug=True, woker=1)
    uvicorn.run(app=app, host="127.0.0.1", port=8080, debug=True)
